import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  let sendLogEvent = require("./WechatAldLog").sendLogEvent;
  
  const VIDEO_AD_ID = "";
  
  let _videoAd;
  let _videoAdLoad = false;
  let _videoOnCloseCallback = null;
  let _videoAdLogKey = null;
  
  if (wx.createRewardedVideoAd !== undefined) {
    _videoAd = wx.createRewardedVideoAd({adUnitId: VIDEO_AD_ID});
    
    _videoAd.onLoad(() => {
      console.log('Video广告加载成功');
      _videoAdLoad = true;
    });
    _videoAd.onError(err => {
      _videoAdLoad = false;
      console.log(err);
    });
    _videoAd.onClose(res => {
      AudioEngineWrapper.resumeAll();
      // 用户点击了【关闭广告】按钮
      // 小于 2.1.0 的基础库版本，res 是一个 undefined
      if (res && res.isEnded || res === undefined) {
        // 正常播放结束，可以下发游戏奖励
        if (_videoAdLogKey) {
          sendLogEvent("视频广告结束(看完) - " + _videoAdLogKey, {
            isEnd: 'true'
          });
        }
        if (_videoOnCloseCallback) {
          _videoOnCloseCallback(true);
          // _videoOnCloseCallback = null;
        }
      } else {
        if (_videoAdLogKey) {
          sendLogEvent("视频广告结束(未看完) - " + _videoAdLogKey, {
            isEnd: 'false'
          });
        }
        if (_videoOnCloseCallback) {
          _videoOnCloseCallback(false);
          // _videoOnCloseCallback = null;
        }
      }
    });
  }
  
  let isVideoAdLoad = function (logKey) {
    if (logKey !== undefined) {
      if (_videoAdLoad) {
        sendLogEvent("无可用视频广告 - " + logKey);
      }
    }
    return _videoAdLoad;
  };
  
  let showVideoAd = function (logKey, callback) {
    if (logKey !== undefined) {
      sendLogEvent("视频广告开始 - " + logKey);
    }
    
    if (_videoAd !== undefined) {
      _videoOnCloseCallback = callback;
      _videoAdLogKey = logKey;
      if (_videoAdLoad) {
        AudioEngineWrapper.pauseAll();
        _videoAd.show().catch((err) => {
          console.log('激励视频广告显示失败', err);
          //加载失败, 重新尝试一次拉取, 并显示
          _videoAd.load()
            .then(() => {
              //重新拉取成功, 播放
              _videoAd.show();
            })
        })
      }
    }
  };
  
  
  module.exports = {
    showVideoAd,
    isVideoAdLoad,
  }
}